package com.hyd.tweet.twitter;

import com.hyd.tweet.AppException;
import com.hyd.tweet.util.Cache;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.User;

/**
 * (description)
 *
 * @author yiding.he
 */
public class TwitterUserUtils {

    public static User getTwitterUser(String account, String screenName) {
        try {
            String cacheKey = "twitterUser:" + screenName;

            if (!Cache.containsKey(cacheKey)) {
                Twitter twitter = TwitterUtils.getTwitter(account);

                if (twitter != null) {
                    User user = twitter.showUser(screenName);
                    Cache.put(cacheKey, user);
                    return user;
                } else {
                    return null;
                }
            } else {
                return Cache.get(cacheKey);
            }
        } catch (TwitterException e) {
            throw new AppException(e);
        }
    }

    public static User getCurrentTwitterUser(String account) {
        try {
            String cacheKey = "twitterUser:account:" + account;

            if (!Cache.containsKey(cacheKey)) {
                Twitter twitter = TwitterUtils.getTwitter(account);
                
                if (twitter != null) {
                    User user = twitter.showUser(twitter.getId());
                    Cache.put(cacheKey, user);
                    return user;
                } else {
                    return null;
                }
            } else {
                return Cache.get(cacheKey);
            }
        } catch (TwitterException e) {
            throw new AppException(e);
        }
    }

    public static User getCurrentTwitterUser(com.hyd.tweet.user.User user) {
        try {
            String cacheKey = "twitterUser:account:" + user.getAccount();

            if (!Cache.containsKey(cacheKey)) {
                Twitter twitter = TwitterUtils.getTwitter(user);
                
                if (twitter != null) {
                    User tuser = twitter.showUser(twitter.getId());
                    Cache.put(cacheKey, tuser);
                    return tuser;
                } else {
                    return null;
                }
            } else {
                return Cache.get(cacheKey);
            }
        } catch (TwitterException e) {
            throw new AppException(e);
        }
    }
}
